// 修改起始和结束塔的选择逻辑，允许任何类型的杆塔
// 同时优化中间杆塔的自动填充逻辑

import React, { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { X, Save, ArrowRight, Info } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Checkbox } from "@/components/ui/checkbox";
import { DictTypeAPI, DictDataAPI } from "@/api/dictionary";

// 解析杆塔编号，提取分支前缀（不区分大小写）和序号
const parseTowerNumber = (towerNumber) => {
  if (!towerNumber) return { branch: "", number: 0 };

  // 匹配字母前缀（1个或多个字母）和数字部分，忽略大小写
  const match = towerNumber.match(/^([A-Za-z]+)(\d+)$/i);
  if (match && match.length === 3) {
    return {
      branch: match[1].toUpperCase(),
      number: parseInt(match[2], 10),
    };
  }

  // 处理纯数字编号（无前缀）的情况
  if (/^\d+$/.test(towerNumber)) {
    return { branch: "", number: parseInt(towerNumber, 10) };
  }

  return { branch: towerNumber.toUpperCase(), number: 0 };
};

// 生成指定范围内的杆塔编号（根据前缀匹配情况）
const generateTowerNumbers = (start, end) => {
  const startParsed = parseTowerNumber(start);
  const endParsed = parseTowerNumber(end);

  // 前缀不同时，直接返回空数组
  if (startParsed.branch !== endParsed.branch) {
    return [];
  }

  // 确保起始序号小于结束序号
  const minNum = Math.min(startParsed.number, endParsed.number);
  const maxNum = Math.max(startParsed.number, endParsed.number);

  // 生成中间杆塔编号
  const towerNumbers = [];
  for (let i = minNum + 1; i < maxNum; i++) {
    towerNumbers.push(
      startParsed.branch ? `${startParsed.branch}${i}` : `${i}`
    );
  }

  // 处理倒序选择的情况
  return startParsed.number > endParsed.number
    ? towerNumbers.reverse()
    : towerNumbers;
};

export default function TensionSectionForm({
  tensionSection,
  projects,
  towers,
  crossingPoints = [],
  onSubmit,
  onCancel,
}) {
  const [formData, setFormData] = useState({
    projectId: "",
    name: "",
    startTensionTowerId: "", // 更改字段名，不再区分耐张塔
    endTensionTowerId: "", // 更改字段名，不再区分耐张塔
    intermediateTowerIds: [],
    associatedCrossingPointIds: [],
    spanLengths: [], // 档距值（数字或空）
    description: "",
  });
  // 下拉框使用筛选后的塔数据
  const [availableTowers, setAvailableTowers] = useState([]);
  const [isManualInput, setIsManualInput] = useState([]);

  // 初始化所有塔数据（直接使用传入的towers，不做筛选）
  useEffect(() => {
    // 初始时如果有tensionSection，根据其projectId筛选
    if (tensionSection?.projectId) {
      setFormData((prev) => ({ ...prev, projectId: tensionSection.projectId }));
    } else if (projects.length > 0) {
      // 否则默认选中第一个项目
      setFormData((prev) => ({ ...prev, projectId: projects[0].id }));
    }
  }, [tensionSection, projects]);

  // 根据项目筛选杆塔（核心修改：实时根据选中的projectId筛选）
  useEffect(() => {
    if (formData.projectId && towers) {
      // 筛选出当前项目的所有杆塔（不限制类型）
      const filtered = towers.filter(tower => tower.projectId === formData.projectId);
      setAvailableTowers(filtered);

      // 如果当前选择的起始/结束塔不在筛选结果中，清空选择
      if (formData.startTensionTowerId && !filtered.some(t => t.id === formData.startTensionTowerId)) {
        setFormData(prev => ({ ...prev, startTensionTowerId: "" }));
      }
      if (formData.endTensionTowerId && !filtered.some(t => t.id === formData.endTensionTowerId)) {
        setFormData(prev => ({ ...prev, endTensionTowerId: "" }));
      }
      // 清空中间杆塔（项目变化后中间杆塔可能无效）
      setFormData(prev => ({ ...prev, intermediateTowerIds: [] }));
      setAutoFilled(false);
    } else {
      setAvailableTowers([]);
      setFormData(prev => ({
        ...prev,
        startTensionTowerId: "",
        endTensionTowerId: "",
        intermediateTowerIds: []
      }));
      setAutoFilled(false);
    }
  }, [formData.projectId, towers]);

  const [orderedTowerIds, setOrderedTowerIds] = useState([]);
  const [availableCrossingPoints, setAvailableCrossingPoints] = useState([]);
  const [crossingTypeMap, setCrossingTypeMap] = useState([]);
  const [loadingCrossingTypes, setLoadingCrossingTypes] = useState(true);
  const [autoFilled, setAutoFilled] = useState(false);
  const [prefixMismatch, setPrefixMismatch] = useState(false);

  // 获取跨越类型数据
  useEffect(() => {
    const fetchCrossingTypes = async () => {
      try {
        setLoadingCrossingTypes(true);
        const typeResponse = await DictTypeAPI.getList();
        const crossingType = typeResponse.rows?.find(
          (item) => item.dictName === "跨越类型"
        );
        if (!crossingType) throw new Error("未找到'跨越类型'字典");

        const dataResponse = await DictDataAPI.getList({
          dictType: crossingType.dictType,
        });
        const validTypes = (dataResponse.rows || [])
          .filter((item) => item.dictValue && item.dictLabel)
          .map((item) => ({
            value: item.dictValue,
            label: item.dictLabel,
          }));

        setCrossingTypeMap(validTypes);
      } catch (error) {
        console.error("获取跨越类型失败:", error);
        setCrossingTypeMap([]);
      } finally {
        setLoadingCrossingTypes(false);
      }
    };

    fetchCrossingTypes();
  }, []);

  // 杆塔类型标签，仅用于显示
  const towerTypeLabels = {
    tensionTower: "耐张塔",
    straightLineTower: "直线塔",
    angleTower: "转角塔",
    branchTower: "分支塔",
  };

  // 初始化表单数据（修复编辑时档距顺序）
  useEffect(() => {
    if (tensionSection) {
      const initialStartId = tensionSection.startTensionTowerId || "";
      const initialEndId = tensionSection.endTensionTowerId || "";
      // 编辑时只允许选择当前项目的杆塔
      const isValidId = (id) => availableTowers.some((t) => t.id === id);
      const validStartId = isValidId(initialStartId) ? initialStartId : "";
      const validEndId = isValidId(initialEndId) ? initialEndId : "";

      const initialCrossingIds = Array.isArray(
        tensionSection.associatedCrossingPointIds
      )
        ? tensionSection.associatedCrossingPointIds.map((id) => String(id))
        : [];

      // 关键：编辑时按 起始塔→中间塔→结束塔 的顺序重新排序档距
      const initialTowerOrder = [
        validStartId,
        ...(tensionSection.intermediateTowerIds || []),
        validEndId,
      ];
      const initialSpanCount = initialTowerOrder.length - 1;
      // 截取或补充档距数组，确保长度与杆塔顺序匹配
      const orderedSpanLengths = Array.isArray(tensionSection.spanLengths)
        ? tensionSection.spanLengths.slice(0, initialSpanCount) // 截断超长部分
        : [];
      // 不足部分补空（避免索引越界）
      while (orderedSpanLengths.length < initialSpanCount) {
        orderedSpanLengths.push("");
      }

      setFormData({
        projectId: tensionSection.projectId || "",
        name: tensionSection.name || "",
        startTensionTowerId: validStartId,
        endTensionTowerId: validEndId,
        intermediateTowerIds: tensionSection.intermediateTowerIds?.filter(id => isValidId(id)) || [],
        associatedCrossingPointIds: initialCrossingIds,
        spanLengths: orderedSpanLengths.map((val) => parseFloat(val) || ""), // 确保数值类型
        description: tensionSection.description || "",
      });
      // 标记手动输入状态（编辑时默认所有已有档距为手动输入）
      setIsManualInput(orderedSpanLengths.map(() => true));
      setAutoFilled(!!tensionSection.intermediateTowerIds?.length);
    } else if (projects.length > 0 && !formData.projectId) {
      setFormData((prev) => ({ ...prev, projectId: projects[0].id }));
    }
  }, [tensionSection, projects, availableTowers]); // 依赖availableTowers确保筛选有效

  // 检查towers重复id（调试用）
  useEffect(() => {
    if (towers && towers.length > 0) {
      const ids = towers.map((t) => t.id);
      const duplicates = [
        ...new Set(ids.filter((id, index) => ids.indexOf(id) !== index)),
      ];
      if (duplicates.length > 0) {
        console.warn("towers中存在重复id:", duplicates);
      }
    }
  }, [towers]);

  // 检查前缀匹配状态，不匹配时清空中间杆塔
  useEffect(() => {
    if (!formData.startTensionTowerId || !formData.endTensionTowerId) {
      setPrefixMismatch(false);
      return;
    }

    // 获取起始和结束塔的编号（从筛选后的availableTowers中查找）
    const startTower = availableTowers.find(
      (t) => t.id === formData.startTensionTowerId
    );
    const endTower = availableTowers.find(
      (t) => t.id === formData.endTensionTowerId
    );

    if (
      !startTower ||
      !endTower ||
      !startTower.towerNumber ||
      !endTower.towerNumber
    ) {
      setPrefixMismatch(false);
      return;
    }

    // 解析前缀
    const startParsed = parseTowerNumber(startTower.towerNumber);
    const endParsed = parseTowerNumber(endTower.towerNumber);

    // 前缀不匹配时，清空中间杆塔
    if (startParsed.branch !== endParsed.branch) {
      setPrefixMismatch(true);
      if (formData.intermediateTowerIds.length > 0) {
        setFormData((prev) => ({ ...prev, intermediateTowerIds: [] }));
        setAutoFilled(false);
      }
    } else {
      setPrefixMismatch(false);
    }
  }, [
    formData.startTensionTowerId,
    formData.endTensionTowerId,
    availableTowers,
  ]);

  // 自动填充中间杆塔（仅当前缀匹配时）
  useEffect(() => {
    // 前缀不匹配、未选起止塔或已填充过，不执行
    if (
      prefixMismatch ||
      !formData.startTensionTowerId ||
      !formData.endTensionTowerId ||
      autoFilled ||
      availableTowers.length === 0
    ) {
      return;
    }

    // 获取起始和结束塔的编号（从筛选后的availableTowers中查找）
    const startTower = availableTowers.find(
      (t) => t.id === formData.startTensionTowerId
    );
    const endTower = availableTowers.find(
      (t) => t.id === formData.endTensionTowerId
    );

    if (
      startTower &&
      endTower &&
      startTower.towerNumber &&
      endTower.towerNumber
    ) {
      // 生成中间杆塔编号列表
      const intermediateNumbers = generateTowerNumbers(
        startTower.towerNumber,
        endTower.towerNumber
      );

      if (intermediateNumbers.length > 0) {
        // 根据编号查找对应的杆塔ID（从当前项目的availableTowers中查找）
        const intermediateIds = intermediateNumbers
          .map((num) => {
            const tower = availableTowers.find((t) => t.towerNumber === num);
            return tower ? tower.id : null;
          })
          .filter(
            (id) =>
              id !== null &&
              id !== formData.startTensionTowerId &&
              id !== formData.endTensionTowerId
          );

        // 更新中间杆塔（去重）
        const uniqueIntermediates = [...new Set(intermediateIds)];
        setFormData((prev) => ({
          ...prev,
          intermediateTowerIds: uniqueIntermediates,
        }));
        setAutoFilled(true);
      }
    }
  }, [
    formData.startTensionTowerId,
    formData.endTensionTowerId,
    availableTowers,
    autoFilled,
    prefixMismatch,
  ]);

  // 关联跨越点筛选（根据当前项目筛选）
  useEffect(() => {
    if (
      formData.projectId &&
      crossingPoints &&
      orderedTowerIds.length >= 2 &&
      towers
    ) {
      // 筛选出当前项目的跨越点
      const projectCrossingPoints = crossingPoints.filter(cp => cp.projectId === formData.projectId);
      console.log(crossingPoints,'crossingPointscrossingPointscrossingPoints');
      
      // 获取当前张力段包含的所有杆塔编号
      const allTowerNumbersInTensionSection = new Set(
        orderedTowerIds
          .map((id) => {
            const tower = towers.find((t) => t.id === id);
            return tower ? tower.towerNumber : null;
          })
          .filter(Boolean)
      );

      // 筛选出当前项目且杆塔在张力段范围内的跨越点
      const filtered = projectCrossingPoints.filter((cp) => {
        // 获取跨越点关联的左右杆塔编号
        const cpLeftTowerNumber = cp.towerLeft?.towerNumber;
        const cpRightTowerNumber = cp.towerRight?.towerNumber;

        // 没有关联杆塔的跨越点也纳入范围
        if (!cpLeftTowerNumber && !cpRightTowerNumber) return true;

        // 检查是否有任一关联杆塔在当前张力段内
        const isLeftTowerInSection =
          cpLeftTowerNumber &&
          allTowerNumbersInTensionSection.has(cpLeftTowerNumber);
        const isRightTowerInSection =
          cpRightTowerNumber &&
          allTowerNumbersInTensionSection.has(cpRightTowerNumber);

        return isLeftTowerInSection || isRightTowerInSection;
      });

      setAvailableCrossingPoints(filtered);
    } else {
      setAvailableCrossingPoints([]);
    }
  }, [formData.projectId, crossingPoints, orderedTowerIds, towers]);

  // 杆塔顺序与档距值联动
  useEffect(() => {
    if (formData.startTensionTowerId && formData.endTensionTowerId) {
      // 生成当前杆塔顺序数组（严格按 起始塔 → 中间塔 → 结束塔 排序）
      const currentTowerIds = [
        formData.startTensionTowerId,
        ...formData.intermediateTowerIds,
        formData.endTensionTowerId,
      ].filter((id, index, self) => self.indexOf(id) === index); // 去重

      // 计算当前需要的档距数量（杆塔数 - 1）
      const requiredSpanCount = currentTowerIds.length - 1;
      const newSpans = [];
      const newManual = [];

      // 关键：按新的杆塔顺序重新构建档距数组
      for (let i = 0; i < requiredSpanCount; i++) {
        // 保留已有相同位置的手动输入值（若存在）
        if (i < formData.spanLengths.length) {
          newSpans.push(formData.spanLengths[i]);
          newManual.push(isManualInput[i] || false);
        } else {
          // 新增档距初始为空
          newSpans.push("");
          newManual.push(false);
        }
      }

      // 仅当：非手动输入 且 输入框为空 时，使用spanToNextTower自动填充
      for (let i = 0; i < requiredSpanCount; i++) {
        const currentTowerId = currentTowerIds[i];
        const currentTower = availableTowers.find((t) => t.id === currentTowerId);

        if (
          !newManual[i] &&
          newSpans[i] === "" &&
          currentTower &&
          currentTower.spanToNextTower
        ) {
          newSpans[i] = Number(currentTower.spanToNextTower);
        }
      }

      // 更新状态（确保档距数组与杆塔顺序严格对应）
      setOrderedTowerIds(currentTowerIds);
      setFormData((prev) => ({ ...prev, spanLengths: newSpans }));
      setIsManualInput(newManual);
    } else {
      // 清空状态
      setOrderedTowerIds([]);
      setFormData((prev) => ({ ...prev, spanLengths: [] }));
      setIsManualInput([]);
    }
  }, [
    formData.startTensionTowerId,
    formData.endTensionTowerId,
    formData.intermediateTowerIds, // 中间塔变化时强制重新计算顺序
    availableTowers, // 依赖筛选后的杆塔数据
  ]);

  // 处理表单变更（重置自动填充状态）
  const handleChange = (field, value) => {
    if (field === "startTensionTowerId" || field === "endTensionTowerId") {
      setAutoFilled(false);
      // 重置手动输入标记（起止塔变更时，重新允许自动填充）
      setIsManualInput([]);
    }
    // 项目变化时清空相关选择
    if (field === "projectId") {
      setAutoFilled(false);
      setIsManualInput([]);
    }
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  // 处理跨越点选择
  const handleCrossingPointToggle = (cpId) => {
    // 统一ID为字符串类型，避免数字/字符串类型不匹配导致的判断错误
    const stringId = String(cpId);

    setFormData((prev) => {
      const current = new Set(prev.associatedCrossingPointIds || []);

      if (current.has(stringId)) {
        current.delete(stringId);
      } else {
        current.add(stringId);
      }

      return {
        ...prev,
        associatedCrossingPointIds: Array.from(current),
      };
    });
  };

  // 添加中间杆塔（只能添加当前项目的杆塔）
  const handleAddIntermediateTower = (towerId) => {
    if (
      towerId &&
      !formData.intermediateTowerIds.includes(towerId) &&
      towerId !== formData.startTensionTowerId &&
      towerId !== formData.endTensionTowerId &&
      // 确保是当前项目的杆塔
      availableTowers.some(t => t.id === towerId)
    ) {
      setFormData((prev) => ({
        ...prev,
        intermediateTowerIds: [...prev.intermediateTowerIds, towerId],
      }));
    }
  };

  // 移除中间杆塔
  const handleRemoveIntermediateTower = (towerId) => {
    setFormData((prev) => ({
      ...prev,
      intermediateTowerIds: prev.intermediateTowerIds.filter(
        (id) => id !== towerId
      ),
    }));
  };

  // 处理档距值变更（标记手动输入）
  const handleSpanLengthChange = (index, value) => {
    const numValue = value === "" ? "" : parseFloat(value);
    setFormData((prev) => {
      const newSpans = [...prev.spanLengths];
      if (index >= 0 && index < newSpans.length) {
        newSpans[index] = isNaN(numValue) ? "" : numValue;
      }
      return { ...prev, spanLengths: newSpans };
    });

    // 标记该索引为手动输入（即使输入为空，也视为用户主动清空）
    setIsManualInput((prev) => {
      const newManual = [...prev];
      newManual[index] = true; // 只要用户操作过输入框，就标记为手动
      return newManual;
    });
  };

  // 计算代表档距
  const calculateRulingSpan = (spans) => {
    if (!spans || spans.length === 0) return 0;
    const validSpans = spans.filter((s) => s > 0);
    if (validSpans.length === 0) return 0;

    const sumCubed = validSpans.reduce((sum, l) => sum + Math.pow(l, 3), 0);
    const sumLinear = validSpans.reduce((sum, l) => sum + l, 0);
    return Math.sqrt(sumCubed / sumLinear);
  };

  // 提交表单（优化校验）
  const handleSubmit = (e) => {
    e.preventDefault();

    // 提交前将空值转为0，并校验是否有无效值
    const validatedSpans = formData.spanLengths.map((s) => {
      const num = parseFloat(s);
      return isNaN(num) || num <= 0 ? 0 : num;
    });

    const hasEmptySpan = validatedSpans.some((s) => s <= 0);
    if (hasEmptySpan) {
      alert("请填写所有有效的档距长度（大于0）");
      return;
    }

    const calculatedRulingSpan = calculateRulingSpan(validatedSpans);
    const totalLength = validatedSpans.reduce((sum, l) => sum + l, 0);

    const submitData = {
      ...formData,
      spanLengths: validatedSpans, // 提交转换后的数字值
      calculatedRulingSpan,
      totalLength,
      id: tensionSection?.id || "",
    };

    onSubmit(submitData);
  };

  // 获取杆塔显示文本（包含类型但不影响功能）
  const getTowerLabel = (towerId) => {
    const tower = availableTowers.find((t) => t.id === towerId);
    if (!tower) return towerId;
    return `${tower.towerNumber} (${
      towerTypeLabels[tower.type] || tower.type
    })`;
  };

  // 获取跨越点显示信息
  const getCrossingPointLabel = (cp) => {
    const typeItem = crossingTypeMap.find(
      (item) => item.value === cp.crossingType
    );
    const typeName = loadingCrossingTypes
      ? "加载中..."
      : typeItem?.label || cp.crossingType;

    const difficultyColors = {
      low: "text-green-600",
      medium: "text-yellow-600",
      high: "text-orange-600",
      critical: "text-red-600",
    };

    return {
      name: cp.name,
      type: typeName,
      difficulty: cp.difficultyLevel,
      difficultyColor: difficultyColors[cp.difficultyLevel] || "text-gray-600",
      object: cp.crossingObject,
    };
  };

  const canShowSpanInputs = orderedTowerIds.length >= 2;
  const totalValidSpans = formData.spanLengths
    .filter((s) => s > 0)
    .reduce((sum, s) => sum + s, 0);

  const hasAutoFilledIntermediates =
    formData.intermediateTowerIds.length > 0 && autoFilled;

  return (
    <Card className="mb-6 shadow-lg border-0">
      <CardHeader className="bg-gradient-to-r from-green-50 to-teal-50 border-b">
        <CardTitle className="flex items-center justify-between">
          <span>{tensionSection ? "编辑勘查单" : "新建勘查单"}</span>
          <Button variant="ghost" size="icon" onClick={onCancel}>
            <X className="w-4 h-4" />
          </Button>
        </CardTitle>
      </CardHeader>

      <CardContent className="p-6">
        <form onSubmit={handleSubmit} className="space-y-6">
          {/* 基本信息 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="projectId">所属项目 *</Label>
              <Select
                value={formData.projectId}
                onValueChange={(value) => handleChange("projectId", value)}
              >
                <SelectTrigger>
                  <SelectValue placeholder="选择项目" />
                </SelectTrigger>
                <SelectContent>
                  {projects.map((p) => (
                    <SelectItem key={`project-${p.id}`} value={p.id}>
                      {p.projectName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label htmlFor="name">勘查单名称 *</Label>
              <Input
                id="name"
                value={formData.name}
                onChange={(e) => handleChange("name", e.target.value)}
                placeholder="如: 1#~5#杆勘查单"
                required
              />
            </div>
          </div>

          {/* 起止塔（不再限制类型，仅显示当前项目的杆塔） */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="startTensionTowerId">起始塔 *</Label>
              <Select
                value={formData.startTensionTowerId}
                onValueChange={(value) =>
                  handleChange("startTensionTowerId", value)
                }
                disabled={!formData.projectId} // 未选项目时禁用
              >
                <SelectTrigger>
                  <SelectValue placeholder={formData.projectId ? "选择起始塔" : "请先选择项目"} />
                </SelectTrigger>
                <SelectContent>
                  {/* 只显示当前项目的杆塔 */}
                  {availableTowers.map((t) => (
                    <SelectItem key={`start-tower-${t.id}`} value={t.id}>
                      {t.towerNumber} ({towerTypeLabels[t.type] || t.type})
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label htmlFor="endTensionTowerId">结束塔 *</Label>
              <Select
                value={formData.endTensionTowerId}
                onValueChange={(value) =>
                  handleChange("endTensionTowerId", value)
                }
                disabled={!formData.projectId} // 未选项目时禁用
              >
                <SelectTrigger>
                  <SelectValue placeholder={formData.projectId ? "选择结束塔" : "请先选择项目"} />
                </SelectTrigger>
                <SelectContent>
                  {/* 只显示当前项目的杆塔 */}
                  {availableTowers.map((t) => (
                    <SelectItem key={`end-tower-${t.id}`} value={t.id}>
                      {t.towerNumber} ({towerTypeLabels[t.type] || t.type})
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          {/* 中间杆塔（只能添加当前项目的杆塔） */}
          <div>
            <div className="flex items-center justify-between mb-2">
              <Label>中间杆塔（按顺序添加）</Label>
              {hasAutoFilledIntermediates && !prefixMismatch && (
                <Badge className="bg-blue-100 text-blue-800 hover:bg-blue-200">
                  已自动识别中间杆塔
                </Badge>
              )}
            </div>

            <div className="flex gap-2 mb-2">
              <Select
                onValueChange={handleAddIntermediateTower}
                disabled={prefixMismatch || !formData.projectId}
              >
                <SelectTrigger className="flex-1">
                  <SelectValue
                    placeholder={
                      !formData.projectId
                        ? "请先选择项目"
                        : prefixMismatch
                        ? "前缀不同，无法添加"
                        : "添加中间杆塔"
                    }
                  />
                </SelectTrigger>
                <SelectContent>
                  {availableTowers
                    .filter(
                      (t) =>
                        t.id !== formData.startTensionTowerId &&
                        t.id !== formData.endTensionTowerId &&
                        !formData.intermediateTowerIds.includes(t.id)
                    )
                    .map((t) => (
                      <SelectItem
                        key={`intermediate-select-${t.id}`}
                        value={t.id}
                      >
                        {t.towerNumber + "(" + towerTypeLabels[t.type] + ")"}
                      </SelectItem>
                    ))}
                </SelectContent>
              </Select>
            </div>
            <div className="flex flex-wrap gap-2">
              {formData.intermediateTowerIds.map((towerId, index) => (
                <Badge
                  key={`intermediate-badge-${towerId}-${index}`}
                  variant="secondary"
                  className="flex items-center gap-1"
                >
                  <span className="text-xs text-gray-500">#{index + 1}</span>
                  {getTowerLabel(towerId)}
                  <button
                    type="button"
                    onClick={() => handleRemoveIntermediateTower(towerId)}
                    className="ml-1 hover:text-red-600"
                  >
                    <X className="w-3 h-3" />
                  </button>
                </Badge>
              ))}
            </div>
          </div>

          {/* 杆塔顺序与档距输入 */}
          {canShowSpanInputs && (
            <div className="space-y-4">
              <Alert className="bg-blue-50 border-blue-200">
                <Info className="h-4 w-4 text-blue-600" />
                <AlertDescription className="text-blue-800">
                  系统已识别到 {orderedTowerIds.length} 个杆塔，需要输入{" "}
                  {orderedTowerIds.length - 1} 个档距长度
                </AlertDescription>
              </Alert>

              <div>
                <Label className="text-base font-semibold mb-3 block">
                  杆塔顺序与档距输入
                </Label>
                <div className="space-y-3">
                  {orderedTowerIds.map((towerId, index) => (
                    <div key={`tower-preview-${towerId}-${index}`}>
                      <div className="flex items-center gap-2 p-3 bg-gray-50 rounded-lg">
                        <Badge variant="outline" className="font-mono">
                          {index + 1}
                        </Badge>
                        <span className="font-medium">
                          {getTowerLabel(towerId)}
                        </span>
                      </div>
                      {index < orderedTowerIds.length - 1 && (
                        <div className="flex items-center gap-3 my-2 ml-8">
                          <ArrowRight className="w-4 h-4 text-gray-400" />
                          <div className="flex-1">
                            <Label className="text-sm text-gray-600">
                              第 {index + 1} 档距 (m) *
                            </Label>
                            <Input
                              type="number"
                              step="0.1"
                              min="0"
                              // 严格使用当前索引对应的档距值
                              value={formData.spanLengths[index] ?? ""}
                              onChange={(e) =>
                                handleSpanLengthChange(index, e.target.value)
                              }
                              placeholder="输入档距长度"
                              className="mt-1"
                              required
                            />
                          </div>
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </div>

              {totalValidSpans > 0 && (
                <div className="p-4 bg-green-50 rounded-lg border border-green-200">
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div>
                      <span className="text-gray-600">已填写档距：</span>
                      <span className="font-bold text-green-700 ml-2">
                        {formData.spanLengths.filter((s) => s > 0).length} /{" "}
                        {orderedTowerIds.length - 1}
                      </span>
                    </div>
                    <div>
                      <span className="text-gray-600">总长度：</span>
                      <span className="font-bold text-green-700 ml-2">
                        {totalValidSpans} m
                      </span>
                    </div>
                    {formData.spanLengths.filter((s) => s > 0).length ===
                      orderedTowerIds.length - 1 && (
                      <>
                        <div>
                          <span className="text-gray-600">代表档距：</span>
                          <span className="font-bold text-green-700 ml-2">
                            {calculateRulingSpan(formData.spanLengths).toFixed(
                              2
                            )}{" "}
                            m
                          </span>
                        </div>
                        <div>
                          <span className="text-gray-600">平均档距：</span>
                          <span className="font-bold text-green-700 ml-2">
                            {(
                              totalValidSpans /
                              formData.spanLengths.filter((s) => s > 0).length
                            ).toFixed(2)}{" "}
                            m
                          </span>
                        </div>
                      </>
                    )}
                  </div>
                </div>
              )}
            </div>
          )}

          {/* 关联跨越点选择（只显示当前项目的跨越点） */}
          {availableCrossingPoints.length > 0 && (
            <div>
              <Label className="text-base font-semibold mb-3 block">
                关联跨越点（可选）
              </Label>
              <p className="text-sm text-gray-600 mb-3">
                选择此勘查单范围内的跨越点共 {availableCrossingPoints.length}{" "}
                个可选）
              </p>
              <div className="border rounded-lg p-4 max-h-60 overflow-y-auto space-y-2 bg-gray-50">
                {availableCrossingPoints.map((cp) => {
                  const cpInfo = getCrossingPointLabel(cp);

                  return (
                    <div
                      key={`crossing-point-${cp.id}`}
                      className="flex items-start space-x-2 p-2 hover:bg-white rounded transition-colors"
                    >
                      <Checkbox
                        id={`cp_${cp.id}`}
                        checked={formData.associatedCrossingPointIds?.includes(
                          String(cp.id)
                        )}
                        onCheckedChange={() => handleCrossingPointToggle(cp.id)}
                        className="mt-1"
                      />
                      <Label
                        htmlFor={`cp_${cp.id}`}
                        className="flex-1 cursor-pointer"
                      >
                        <div className="flex items-center gap-2 flex-wrap">
                          <span className="font-medium">{cpInfo.name}</span>
                          <Badge variant="outline" className="text-xs">
                            {cpInfo.type}
                          </Badge>
                          {(cp.difficultyLevel === "high" ||
                            cp.difficultyLevel === "critical") && (
                            <Badge className="bg-red-100 text-red-800 text-xs">
                              {cp.difficultyLevel === "critical"
                                ? "极高难度"
                                : "高难度"}
                            </Badge>
                          )}
                        </div>
                        {cp.towerLeft?.towerNumber &&
                          cp.towerRight?.towerNumber && (
                            <div className="text-xs text-gray-500 mt-1">
                              {cp.towerLeft.towerNumber} ↔{" "}
                              {cp.towerRight.towerNumber}
                            </div>
                          )}
                      </Label>
                    </div>
                  );
                })}
              </div>
              <p className="text-sm text-gray-500 mt-2">
                已选择 {formData.associatedCrossingPointIds?.length || 0}{" "}
                个跨越点
              </p>
            </div>
          )}

          {/* 描述 */}
          <div>
            <Label htmlFor="description">描述</Label>
            <Textarea
              id="description"
              value={formData.description}
              onChange={(e) => handleChange("description", e.target.value)}
              rows={3}
              placeholder="输入勘查单描述信息..."
            />
          </div>

          <div className="flex justify-end gap-3 pt-4">
            <Button type="button" variant="outline" onClick={onCancel}>
              取消
            </Button>
            <Button
              type="submit"
              className="bg-green-600 hover:bg-green-700"
              disabled={
                !formData.projectId ||
                !canShowSpanInputs ||
                formData.spanLengths.some((s) => !s || s <= 0) ||
                prefixMismatch
              }
            >
              <Save className="w-4 h-4 mr-2" />
              {tensionSection ? "更新勘查单" : "创建勘查单"}
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}